import { useState, useEffect } from 'react';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';
import rehypeSlug from 'rehype-slug';
import { visit } from 'unist-util-visit';

export const useMarkdown = (path: string) => {
    const [html, setHtml] = useState('');
    const [toc, setToc] = useState<{ id: string, text: string, level: number }[]>([]);

    useEffect(() => {
        fetch(path)
            .then(res => res.text())
            .then(markdown => {
                // 处理Markdown并提取目录
                unified()
                    .use(remarkParse)
                    .use(remarkGfm)
                    .use(remarkRehype)
                    .use(rehypeSlug)
                    .use(() => tree => {
                        const headings: any[] = [];
                        visit(tree, 'element', (node: any) => {
                            if (node.tagName.match(/^h[2-4]$/)) {
                                headings.push({
                                    id: node.properties?.id,
                                    text: node.children[0].value,
                                    level: parseInt(node.tagName.charAt(1))
                                });
                            }
                        });
                        setToc(headings);
                    })
                    .use(rehypeStringify)
                    .process(markdown)
                    .then(file => setHtml(String(file)));
            });
    }, [path]);

    return { html, toc };
};